package tech.mobi.child.service;

import java.util.ArrayList;
import java.util.List;

import tech.mobi.child.bean.MainClientAppBean;
import tech.mobi.child.utils.Configuration;
import tech.mobi.child.utils.DBOpenHelper;
import tech.mobi.child.utils.SqliteParser;



import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBService {

	/**
	 * 查询：常用应用 20130912 YangLijun
	 * @param 
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	@SuppressWarnings("finally")
	public static Object getAppList(Object ...objects) {
		MainClientAppBean baseInfoBean = (MainClientAppBean) objects[1];
		List<MainClientAppBean> list = new ArrayList<MainClientAppBean>();
		SQLiteDatabase db = null;
		Cursor cursor = null;
		
		try {
			db = new DBOpenHelper((Context)objects[0]).getReadableDatabase();
			String sql = "select APPID,APPNAME,APPPIC,APPTYPE,PARID,DATABASEID,APPDESC,APPSORT,IS_MYAPP,ID as TYPEID,NAME as TYPENAME from [T_IMOBILE_APPS] t,T_IMOBILE_APPS_TYPE_DIC t1 where t.APPTYPE=t1.ID AND t1.IS_VALID='Y' and t.IS_MYAPP like '"+ baseInfoBean.getIs_myapp().toUpperCase() +"' order by t.APPSORT";
			cursor = db.rawQuery(sql, null);
			SqliteParser sqliteParser = new SqliteParser();
			list = sqliteParser.parseDatabases(cursor,MainClientAppBean.class);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(cursor!=null){
				try {
					cursor.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if(db!=null){
				try {
					db.close();
				} catch (Exception e2) {
					
				}
			}

			return list;
		}
		
	}

	/**
	 * 修改常用应用，20120520 YangLijun
	 * @param objects
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	public static int updateAppItem(Object ...objects){
		MainClientAppBean baseInfoBean = (MainClientAppBean) objects[1];
		String sql = "update T_IMOBILE_APPS set IS_MYAPP='" + baseInfoBean.getIs_myapp().toUpperCase() +"' where [APPID] = "+baseInfoBean.getAppid();
		return update(sql);
	}
	
	
	private static int update(String sql){
		int returnValue = Configuration.FAILED;
		SQLiteDatabase db = MainService.dbOpenHelper.getWritableDatabase();
		try{
			db.execSQL(sql);
			returnValue = Configuration.SUCCEED;
		}finally{

			if(db!=null&&db.isOpen()){
				try {
					db.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return returnValue;
	}
}

